package com.insurance.service.impl;

import java.util.List;
import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.insurance.bean.Proxy;
import com.insurance.service.ProxyService;
import com.insurance.util.PageBean;


@Transactional
public class ProxyServiceBean implements ProxyService {
	@Resource private SessionFactory sessionFactory;

	public void save(Proxy proxy){
		sessionFactory.getCurrentSession().persist(proxy);
	}
	public void update(Proxy proxy){
		sessionFactory.getCurrentSession().merge(proxy);
	}
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Proxy getProxy(Integer proxyid){
		return (Proxy)sessionFactory.getCurrentSession().get(Proxy.class, proxyid);
	}

	public void delete(Integer proxyid){
		sessionFactory.getCurrentSession().delete(
				sessionFactory.getCurrentSession().load(Proxy.class, proxyid));
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	@SuppressWarnings("unchecked")
	public List<Proxy> getProxys(){		
		return sessionFactory.getCurrentSession().createQuery("from Proxy").list();
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)	
	@SuppressWarnings("unchecked")
	public List<Proxy> getProxysByPage(PageBean page){
		
		int first = (page.getCurrentpage() - 1) * page.getPagesize();
		return sessionFactory.getCurrentSession().createQuery("from Proxy p order by p.id desc").
		setFirstResult(first).setMaxResults(page.getPagesize()).list();
		
	}
	
	public int getTotalCount() {
		
		return ((Long)sessionFactory.getCurrentSession().createQuery
				("select count(*) from Proxy").uniqueResult()).intValue();
		
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	@SuppressWarnings("unchecked")
	public List<Proxy> getProxysByType(Integer type){		
		
		return sessionFactory.getCurrentSession().createQuery
		("from Proxy p where p.type=" + type).list();
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	@SuppressWarnings("unchecked")
	public List<Proxy> getProxysByCompany(String companyName){
		
		return sessionFactory.getCurrentSession().createQuery
		("from Proxy where proxy.companyName=" + companyName).list();
		
	}
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	@SuppressWarnings("unchecked")
	public List<Proxy> searchProxy(Proxy proxy){
		String hql = "from Proxy p where p.type = ? and p.companyName = ?";
		return sessionFactory.getCurrentSession().createQuery(hql).list();
	}
}
